from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from .serializers import UserAddressSerializer
from .serializers import CreateUserSerializer, UserDetailSerializers, AddressTitleSerializer
from rest_framework.permissions import IsAuthenticated
from .models import User
from .models import Address
from rest_framework.mixins import UpdateModelMixin
from .serializers import EmailSerializers
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


class UsersView(CreateAPIView):
    '''
    用户注册
    '''
    serializer_class = CreateUserSerializer

    # def post(self,request):
    #     #把请求过来的数据放到序列化其中进行序列化
    #     serializer = self.get_serializer(data=request.data)
    #     #验证序列化值是否有效
    #     serializer.is_value(raise_exception=True)
    #     serializer.save()
    #     return Response(serializer.data,status=status.HTTP_201_CREATED)


class UsernameCountView(APIView):
    '''验证前端传过来的值是否是合法的用户名'''

    def get(self, request, username):
        # 查询user表
        count = User.objects.filter(username=username).count()

        # 包装响应数据
        data = {
            'username': username,
            'count': count
        }
        # 响应
        return Response(data)


class MobileCountView(APIView):
    '''判断手机号码是否合法'''

    def get(self, request, mobile):
        # 查询user表
        count = User.objects.filter(mobile=mobile).count()
        # 包装数据
        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)


class UserDetailView(RetrieveAPIView):
    '''获取单一的用户展示信息'''
    # 1.0定义序列化类
    serializer_class = UserDetailSerializers
    # 这里不指定查询集,直接书写路由/user/,可以提升查询速度
    permission_classes = [IsAuthenticated]

    def get_object(self):
        '''重写父类的方法,这样在执行的时候优先调用子类的get_object方法'''
        return self.request.user


class EmailView(UpdateAPIView):
    '''
    更新用户的邮箱
    '''
    # 1.0判断用户是否是认证用户
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializers

    def get_object(self):
        return self.request.user


class EmailVerifyView(APIView):
    def get(self, request):
        token = request.query_params.get('token')
        user = User.check_verify_email_token(token)
        if not user:
            return Response({'message': '激活失败'}, status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()
        return Response({'message': 'ok'})


class AddressViewSet(UpdateModelMixin, GenericViewSet):
    """用户收货地址增删改查"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer

    # queryset = ''
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)
        # return Address.objects.filter(is_deleted=False)

    def create(self, request):
        user = request.user
        # count = user.addresses.all().count()
        count = Address.objects.filter(user=user).count()
        # 用户收货地址数量有上限  最多只能有20
        if count >= 20:
            return Response({'message': '收货地址数量上限'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建序列化器进行反序列化
        serializer = self.get_serializer(data=request.data)
        # 调用序列化器的is_valid()
        serializer.is_valid(raise_exception=True)
        # 调用序列化器的save()
        serializer.save()
        # 响应
        return Response(serializer.data, status=status.HTTP_201_CREATED)
